package com.ruoyi.kis.service.imp;

import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.kis.Vars.Constants;
import com.ruoyi.kis.Vars.ConstantsAccount;
import com.ruoyi.kis.Vars.ConstantsDanju;
import com.ruoyi.kis.domain.*;
import com.ruoyi.kis.mapper.IkisMapper;
import com.ruoyi.kis.service.IKisService;
import com.ruoyi.kis.util.DanjuNumberUtil;
import com.ruoyi.kis.util.VerifyBaseDataUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;


@Service
@DataSource(DataSourceType.SLAVE)
public class KisServiceImp implements IKisService {
    private static final Logger LOGGER = LoggerFactory.getLogger(KisServiceImp.class);
    @Autowired
    private IkisMapper kisMapper;
    @Override
    public List<IcItems> queryItems(Date currentTime) {
        return null;
    }

    @Override
    public Date queryCurrentTime(String tableName) {
        return kisMapper.queryCurrentTime(tableName);
    }
//
    @Override
    public void updateCurrentTime(Map<String,Object> params) {
        int temp = kisMapper.updateCurrentTime(params);
//        System.out.println(temp);
    }
//
//    @Override
//    public List<PoInStock> queryPoinStock(Date poInStockTime) {
//        return kisMapper.queryPoinStock(poInStockTime);
//    }

    @Override
    public List<OutSourceEntryF> queryOutSourceInWareOrder() {
        List<OutSourceEntryF> outSourceEntryFList = kisMapper.queryOutSourceInWareOrder();
        ListIterator<OutSourceEntryF> outSourceEntryFListIterator = outSourceEntryFList.listIterator();

        while (outSourceEntryFListIterator.hasNext()){
            OutSourceEntryF next = outSourceEntryFListIterator.next();
            List<OutSourceEntryS> entityList = kisMapper.queryOutSourceInWareOrderSById(next.getFInterID());
            next.setFEntity(entityList);
        }
        return outSourceEntryFList;
    }

    @Override
    public List<ProductStoreF> queryProdStore() {
        final List<ProductStoreF> productStoreFS = kisMapper.queryProductStoreF();
        ListIterator<ProductStoreF> productStoreFSIterator = productStoreFS.listIterator();

        while (productStoreFSIterator.hasNext()){
            ProductStoreF next = productStoreFSIterator.next();
            List<ProductStoreS> entityList = kisMapper.queryProductStoreSById(next.getFInterID());
            next.setFEntity(entityList);
        }
        return productStoreFS;
    }

    @Override
    public List<MaterialRequisiteF> queryMaterialRequisiteF() {
        List<MaterialRequisiteF> productStoreFS = kisMapper.queryMaterialRequisiteF();
        ListIterator<MaterialRequisiteF> MaterialRequisiteFIterator = productStoreFS.listIterator();

        while (MaterialRequisiteFIterator.hasNext()){
            MaterialRequisiteF next = MaterialRequisiteFIterator.next();
            List<MaterialRequisiteS> entityList = kisMapper.queryMaterialRequisiteSById(next.getFInterID());
            next.setFEntity(entityList);
        }
        return productStoreFS;
    }

    /**
     * 查询逆向领料单
     * @return
     */
    @Override
    public List<MaterialRequisiteF> queryMaterialRequisiteF_NX() {
        List<MaterialRequisiteF> productStoreFS = kisMapper.queryMaterialRequisiteF_NX();
        ListIterator<MaterialRequisiteF> MaterialRequisiteFIterator = productStoreFS.listIterator();

        while (MaterialRequisiteFIterator.hasNext()){
            MaterialRequisiteF next = MaterialRequisiteFIterator.next();
            List<MaterialRequisiteS> entityList = kisMapper.queryMaterialRequisiteSById_NX(next.getFInterID());
            next.setFEntity(entityList);
        }
        return productStoreFS;
    }
    @Override
    public List<OutboundDelveryOrderF> queryOutboundDelveryOrderF(Date orderTime) {
        final List<OutboundDelveryOrderF> outboundDelveryOrderF = kisMapper.queryOutboundDelveryOrderF(orderTime);
        ListIterator<OutboundDelveryOrderF> outboundDelveryOrderFIterator = outboundDelveryOrderF.listIterator();

        while (outboundDelveryOrderFIterator.hasNext()){
            final OutboundDelveryOrderF next = outboundDelveryOrderFIterator.next();
            List<OutboundDelveryOrderS> entityList = kisMapper.queryOutboundDelveryOrderSById(next.getFInterID());
            next.setFEntity(entityList);
        }
        return outboundDelveryOrderF;
    }

    @Override
    public List<TransferOrderF> queryTransferOrderF() {
        final List<TransferOrderF> transferOrderF = kisMapper.queryTransferOrderF();
        ListIterator<TransferOrderF> transferOrderFIterator = transferOrderF.listIterator();

        while (transferOrderFIterator.hasNext()){
            final TransferOrderF next = transferOrderFIterator.next();
            List<TransferOrderS> entityList = kisMapper.queryTransferOrderSById(next.getFInterID());
            next.setFEntity(entityList);
        }
        return transferOrderF;
    }

    @Override
    public List<IcItems> queryICITEMS(Date orderTime) {
        final List<IcItems> icItems = kisMapper.queryICITEMS(orderTime);
        return icItems;
    }

    @Override
    public List<DispatchOrderF> queryDispatchOrder() {
        final List<DispatchOrderF> dispatchOrderF = kisMapper.queryDispatchOrderF();
        if (dispatchOrderF != null && dispatchOrderF.size() > 0){
            ListIterator<DispatchOrderF> dispatchOrderFIterator = dispatchOrderF.listIterator();

            while (dispatchOrderFIterator.hasNext()){
                final DispatchOrderF next = dispatchOrderFIterator.next();
                List<DispatchOrderS> entityList = kisMapper.queryDispatchOrderSById(next.getFInterID());
                next.setFEntity(entityList);
            }
//            kisMapper.updateKisICStockBillFlag(dispatchOrderF.get(0).getFInterID());
        }

        return dispatchOrderF;
    }

    @Override
    @Transactional
    public Map<String, Object> saveOsInWareOrder(OsInWareOrderF osInWareOrderF) {
        Map<String, Object> result = new HashMap<>();
        List<OsInWareOrderS> fEntityS = osInWareOrderF.getFEntity();


        // 验证FROB FSelTranType是否对应

        boolean isValidType = (osInWareOrderF.getFROB().equals(ConstantsDanju.FROB.BLACK) && osInWareOrderF.getFSelTranType().equals(ConstantsDanju.SLTZD.FTRANTYPE + ""))
                || (osInWareOrderF.getFROB().equals(ConstantsDanju.FROB.RED) && osInWareOrderF.getFSelTranType().equals(ConstantsDanju.TLTZD.FTRANTYPE + ""));
        if (!isValidType) {
            return buildErrorResult(result, "单据类型FROB/FSelTranType不匹配，请核实后重新录入！");
        }
        // 检查上游单据
        for (OsInWareOrderS entity : fEntityS) {
            String billNo = entity.getFBillNo();
            if (billNo.contains(ConstantsDanju.TLTZD.HEAD) || billNo.contains(ConstantsDanju.SLTZD.HEAD)) {
                int usedCount = kisMapper.ifTlOrSlHasBeenUsed(billNo);
                if (usedCount > 0) {
                    return buildErrorResult(result, "上游单据已被使用，请勿重复使用");
                }

                int existCount = kisMapper.ifTlOrSlExist(billNo);
                if (existCount == 0) {
                    return buildErrorResult(result, "上游单据" + billNo + "不存在，请核实后重新录入！");
                }
            }
        }

        // 供应商检查
        String supplierID = VerifyBaseDataUtil.getSupplierID(
            osInWareOrderF.getF_HCH_Text1_ID(),
            osInWareOrderF.getSupplierCode(),
            kisMapper
        );
        if (StringUtils.isEmpty(supplierID)) {
            return buildErrorResult(result, "供应商不存在，请核实后重新录入！");
        }
        osInWareOrderF.setF_HCH_Text1_ID(supplierID);

        // 部门检查
        String deptID = VerifyBaseDataUtil.getDeptID(
            osInWareOrderF.getFDeptID(),
            osInWareOrderF.getFDeptCode(),
            kisMapper
        );
        if (StringUtils.isEmpty(deptID)) {
            return buildErrorResult(result, "部门不存在，请核实后重新录入！");
        }
        osInWareOrderF.setFDeptID(deptID);

        // 生成单据号
        PoDanjuNumber poDanjuNumber = new PoDanjuNumber(
            ConstantsDanju.wglkd.HEAD,
            ConstantsDanju.wglkd.HEAD.length(),
            ConstantsDanju.wglkd.FTRANTYPE
        );
        poDanjuNumber.setHeadyYyyyMMdd(poDanjuNumber.getHead() + poDanjuNumber.getYyyyMMdd());
        int sequence = kisMapper.queryOsInWareOrderFMaxID(poDanjuNumber);
        String wglkdNo = DanjuNumberUtil.getDanjuNumber(
            poDanjuNumber.getHead(),
            poDanjuNumber.getYyyyMMdd(),
            sequence
        );
        osInWareOrderF.setFBillNo(wglkdNo);

        // 保存主表
        String maxFinterID = getNewFinterID(Constants.TABLE_NAME.ICStockBill);
        osInWareOrderF.setFInterID(maxFinterID);
//        if (osInWareOrderF.getID().equals(Constants.ZHIKU.ZhiKu_1)) {
//            osInWareOrderF.setFBillerID(Constants.ZHIKU.ZhiKu_1_FBillerID);
//            osInWareOrderF.setFSManagerID(Constants.ZHIKU.ZhiKu_1_FSManagerID);
//        }
        if (osInWareOrderF.getID().equals(ConstantsAccount.ZhiKu_1_FID)) {
            osInWareOrderF.setFBillerID(ConstantsAccount.ZhiKu_1_FBillerID);
            osInWareOrderF.setFSManagerID(ConstantsAccount.ZhiKu_1_FSManagerID);
        }
        kisMapper.saveOsInWareOrder(osInWareOrderF);
//        kisMapper.updateICMaxNumFinterID(Constants.TABLE_NAME.ICStockBill, Constants.TABLE_NAME.ICStockBill);

        // 保存子表
        AtomicInteger entryId = new AtomicInteger(1);//新生成单据不会有EntryID，所以从1开始递增
        fEntityS.forEach(outSourceEntryS -> {
            outSourceEntryS.setFInterID(osInWareOrderF.getFInterID());
            outSourceEntryS.setFComplexQty(outSourceEntryS.getQuantity() + outSourceEntryS.getCompany());
            outSourceEntryS.setFEntryID(String.valueOf(entryId.getAndIncrement()));
//            String FEntryID = kisMapper.getOutSourceEntrySMaxID(osInWareOrderF.getFInterID());
//            if (StringUtils.isEmpty(FEntryID) || "0".equals(FEntryID)) {
//                outSourceEntryS.setFEntryID(String.valueOf(entryId.getAndIncrement()));
//            } else {
//                outSourceEntryS.setFEntryID(FEntryID);
//            }

            //获取源单据子表的FinterID、FEntryID赋值给外购入库单子表的FSourceInterID、FSourceEntryID
            OsInWareOrderS sourceInfo = VerifyBaseDataUtil.getTlSlId(
                outSourceEntryS.getFBillNo(),
                outSourceEntryS.getFItemID(),
                kisMapper,
                outSourceEntryS.getBatch_Number()
            );
            if (sourceInfo != null) {
                outSourceEntryS.setFSourceInterID(sourceInfo.getFSourceInterID());
                outSourceEntryS.setFSourceEntryID(sourceInfo.getFSourceEntryID());
            }
            /**
             *
             * 设置FPrice，FAuxPrice，FAmout
             *
             */

            if(outSourceEntryS.getFPrice() == null || outSourceEntryS.getFPrice().isEmpty()){
                outSourceEntryS.setFPrice("0");
            }
            if(outSourceEntryS.getFAuxPrice() == null || outSourceEntryS.getFAuxPrice().isEmpty()){
                outSourceEntryS.setFAuxPrice("0");
            }
            if(outSourceEntryS.getFAmount() == null || outSourceEntryS.getFAmount().isEmpty()){
                outSourceEntryS.setFAmount("0");
            }
        });

        int sCount = kisMapper.saveOsInWareOrderS(fEntityS);
        LOGGER.info("保存外购入库单主表: {}", osInWareOrderF);
        LOGGER.info("保存外购入库单子表: {}, 更新记录数: {}", fEntityS, sCount);

        result.put("MSGCODE", "0");
        result.put("MSGNAME", "SUCCESS");
        result.put("MSG", "保存成功");
        return result;
    }




    @Override
    public int updateKisICStockBillFlag(String fInterID,String kisFlag) {
        return kisMapper.updateKisICStockBillFlag(fInterID,kisFlag);
    }
    @Override
    public int updateKisPOInstockFlag(String fInterID,String kisFlag) {
        return kisMapper.updateKisPOInstockFlag(fInterID,kisFlag);
    }

    @Override
    @Transactional
    public Map saveProdStore(SclkdFPo sclkdFPo) {
//        osInWareOrderF.setFInterID(kisMapper.getMaxFinterID(Constants.ICStockBill));
        Map<String,Object> map = new HashMap<>();
        sclkdFPo.setFInterID(getNewFinterID(Constants.TABLE_NAME.ICStockBill));
//      单据编号生成
        String fBillNo = sclkdFPo.getFBillNo();//wms过来的单据号需要与新生成 单据号对应
        PoDanjuNumber poDanjuNumber = new PoDanjuNumber(ConstantsDanju.SCRKD.HEAD,ConstantsDanju.SCRKD.HEAD.length(),ConstantsDanju.SCRKD.FTRANTYPE);//加8：日期长度,+1从后面1位开始计算长度
        poDanjuNumber.setHeadyYyyyMMdd(poDanjuNumber.getHead().concat(poDanjuNumber.getYyyyMMdd()));//用于查询sql
        int sequence = kisMapper.queryOsInWareOrderFMaxID(poDanjuNumber);//查询单据号最后3位最大值
        String scrkdNo = DanjuNumberUtil.getDanjuNumber(poDanjuNumber.getHead(),poDanjuNumber.getYyyyMMdd(),sequence);
        sclkdFPo.setFBillNo(scrkdNo);
        LOGGER.info(scrkdNo + "生产入库单单据号生成完成");
//        if(sclkdFPo.getID().equals(Constants.ZHIKU.ZhiKu_1)){
//            sclkdFPo.setFBillerID(Constants.ZHIKU.ZhiKu_1_FBillerID);
//            sclkdFPo.setFSManagerID(Constants.ZHIKU.ZhiKu_1_FSManagerID);
//        }
        if (sclkdFPo.getID().equals(ConstantsAccount.ZhiKu_1_FID)) {
            sclkdFPo.setFBillerID(ConstantsAccount.ZhiKu_1_FBillerID);
            sclkdFPo.setFSManagerID(ConstantsAccount.ZhiKu_1_FSManagerID);
        }

        //判断无供应商id，则用供应商编码进行查询(生产入库不需要验证供应商)
        /**
         *
         String supplierID = VerifyBaseDataUtil.getSupplierID(sclkdFPo.getFSupplyID() ,sclkdFPo.getSupplierCode() ,kisMapper);
         if(supplierID == null || supplierID.isEmpty()){
         map.put("MSGCODE","1");
         map.put("MSGNAME","ERROR");
         map.put("MSG","供应商或交货单位不存在，请核实后重新录入！");
         return map;
         }else {
         sclkdFPo.setF_HCH_Text1_ID(supplierID);
         }

         *
         */

        //判断部门id是否传过来，没有则用部门编码进行查询（如果都没有则为空）

        String deptID = VerifyBaseDataUtil.getDeptID(sclkdFPo.getFDeptID(),sclkdFPo.getFDeptCode(),kisMapper);
        if(deptID == null || deptID.isEmpty()){
            map.put("MSGCODE","1");
            map.put("MSGNAME","ERROR");
            map.put("MSG","部门不存在，请核实后重新录入！");
            return map;
        }else {
            sclkdFPo.setFDeptID(deptID);
        }



//        //判断无供应商id，则用供应商编码进行查询
//        if(sclkdFPo.getFSupplyID() == null || sclkdFPo.getFSupplyID().isEmpty()){
//            if(sclkdFPo.getSupplierCode() == null || sclkdFPo.getSupplierCode().isEmpty()){
//                map.put("MSGCODE","1");
//                map.put("MSGNAME","ERROR");
//                map.put("MSG","供应商编码为空，请检查");
//                return map;
//            }else {
//                String supplierID = kisMapper.querySupplierIDByCode(sclkdFPo.getSupplierCode());
//                sclkdFPo.setF_HCH_Text1_ID(supplierID);
//            }
//
//        }
//        //判断部门id是否传过来，没有则用部门编码进行查询（如果都没有则为空）
//        if(sclkdFPo.getFDeptID() == null || sclkdFPo.getFDeptID().isEmpty()){
//            if (sclkdFPo.getFDeptCode() != null && !sclkdFPo.getFDeptCode().isEmpty()){
//                String deptID = kisMapper.queryFDeptIDByCode(sclkdFPo.getFDeptCode());
//                sclkdFPo.setFDeptID(deptID);
//            }
//        }







        kisMapper.saveProdStore(sclkdFPo);
//        kisMapper.updateICMaxNumFinterID(Constants.TABLE_NAME.ICStockBill,Constants.TABLE_NAME.ICStockBill);//更新
        List<SclkdSPo> fEntityS = sclkdFPo.getFEntity();
//        int countS = kisMapper.saveProdStoreS(fEntity);
        final int[] entryId = {1}; // 使用数组封装基本类型
        for (SclkdSPo outSourceEntryS : fEntityS) {
            outSourceEntryS.setFInterID(sclkdFPo.getFInterID());
            String FEntryID = kisMapper.getOutSourceEntrySMaxID(sclkdFPo.getFInterID());
            String fItemId = kisMapper.queryItemIdByFNumber(outSourceEntryS.getMaterial_Code());
            if(fItemId == null || fItemId.isEmpty()){
                map.put("MSGCODE","1");
                map.put("MSG","物料编码不存在");
                return map;
            }
            outSourceEntryS.setFItemID(fItemId);
            if(outSourceEntryS.getWarehouse() == null || outSourceEntryS.getWarehouse().isEmpty()){
                if(outSourceEntryS.getWarehouseCode() == null || outSourceEntryS.getWarehouseCode().isEmpty()){
                    map.put("MSGCODE","1");
                    map.put("MSG","仓库编码不存在");
                    return map;
                }else {
                    String warehouseID = kisMapper.queryWarehouseId(outSourceEntryS.getWarehouseCode());
                    outSourceEntryS.setWarehouse(warehouseID);
                }
            }
            if (FEntryID == null || FEntryID.equals("")|| FEntryID.equals("0")){
                outSourceEntryS.setFEntryID(String.valueOf(entryId[0]));
                entryId[0]++;
            }else {
                outSourceEntryS.setFEntryID(FEntryID);
            }
        }
        int sCount = kisMapper.saveProdStoreS(fEntityS);
        map.put("MSGCODE","0");
        map.put("MSGNAME","success");
        map.put("MSG","");
        return map;
    }
    @Override
    @Transactional
    public Map updateProdStore(SclkdFPo sclkdFPo) {
        Map<String,Object> map = new HashMap<>();
        String FBillNo = sclkdFPo.getFBillNo();
        //判断原单据是否已审核
        int icstockBillCheck = isIcstockBillCheck(FBillNo);
        if(icstockBillCheck == ConstantsDanju.DanjuStatus.CHECKED){
            map.put("MSGCODE","1");
            map.put("MSGNAME","error");
            map.put("MSG",FBillNo + "单据已审核，不允许修改！");
            return map;
        }else if(icstockBillCheck == ConstantsDanju.DanjuStatus.NODANJU){//单据不存在
            map.put("MSGCODE","1");
            map.put("MSGNAME","error");
            map.put("MSG",FBillNo + "单据不存在，请核实！");
            return map;
        }
        /**
         * 根据单据号获取FinterID
         */
//        SclkdFPo sclkdFPoTemp = kisMapper.queryFinterIDByFBillNo(sclkdFPo.getFBillNo());
//        final String fInterID = sclkdFPoTemp.getFInterID();
//        if(fInterID == null || fInterID.isEmpty()){
//            map.put("MSGCODE","1");
//            map.put("MSGNAME","error");
//            map.put("MSG","产品入库(红)反馈ERP未获取到FinterID,请核实单据号是否正确！");
//            return map;
//        }else{
//            sclkdFPo.setFInterID(fInterID);
//        }
        /**
         * 判断是否智库1，如果是则设置审核人id（临时不用，反馈ERP后人员审核）
         */
        if(sclkdFPo.getID().equals(Constants.ZHIKU.ZhiKu_1)){
//            sclkdFPo.setFCheckerID(Constants.ZHIKU.ZhiKu_1_FCheckerID);
        }


        List<SclkdSPo> fEntityS = sclkdFPo.getFEntity();
//不需要审核
//        if(sclkdFPo != null && sclkdFPo.getFInterID() != null){
//            int headerCount = kisMapper.updatesclkdF(sclkdFPo);
//        }else{
//            map.put("MSGCODE","1");
//            map.put("MSGNAME","error");
//            map.put("MSG","产品入库(红)反馈ERP未获取到FinterID");
//            return map;
//        }
        if(fEntityS != null && fEntityS.size() > 0){


            for(int i = 0 ; i < fEntityS.size(); i++ ){
                //验证单据如果是红单据，要判断数量为负数
                if(sclkdFPo.getFROB().equals(ConstantsDanju.FROB.RED)){
                    String FAuxQty = fEntityS.get(i).getFAuxQty();
                    String FAuxQtyMust = fEntityS.get(i).getFAuxQtyMust();
                    BigDecimal fSecQty = fEntityS.get(i).getFSecQty();
                    if(
                            (FAuxQty != null && Float.parseFloat(FAuxQty) > 0) ||
                            (FAuxQtyMust != null && Float.parseFloat(FAuxQtyMust) > 0) ||
                            (fSecQty != null && fSecQty.compareTo(BigDecimal.ZERO) > 0)
                    ){
                        map.put("MSGCODE","1");
                        map.put("MSGNAME","error");
                        map.put("MSG","产品入库(红)反馈：红色单据表体明细重量数据要使用负数");
                        return map;
                    }
                }
                //根据物料编码获取FItemID
                String FItemID = kisMapper.queryItemIdByFNumber(fEntityS.get(i).getMaterial_Code());
                if(FItemID == null || FItemID.isEmpty()){
                    map.put("MSGCODE","1");
                    map.put("MSGNAME","error");
                    map.put("MSG",fEntityS.get(i).getMaterial_Name() + "物料编码不存在");
                    return map;

                }else {
                    fEntityS.get(i).setFItemID(FItemID);
                }
                if(sclkdFPo.getFROB().equals(ConstantsDanju.FROB.RED)){
                    String FAuxQty = fEntityS.get(i).getFAuxQty();
                    String FAuxQtyMust = fEntityS.get(i).getFAuxQty();
                    BigDecimal fSecQty = fEntityS.get(i).getFSecQty();
                    if(FAuxQty != null && Float.parseFloat(FAuxQty) > 0 ||
                            FAuxQtyMust != null && Float.parseFloat(FAuxQtyMust) > 0 ||
                            fSecQty != null && fSecQty.compareTo(BigDecimal.ZERO) > 0
                    ){
                        map.put("MSGCODE","1");
                        map.put("MSGNAME","error");
                        map.put("MSG","产品入库(红)反馈：红色单据表体明细重量数据要使用负数");
                        return map;
                    }
                }
                //获取FinterID和FEntryID,此处应该用生产入库单子表数据，但只取FinterID和FEntryID，用这个获取即可
                MaterialRequisiteS materialRequisiteS = kisMapper.queryFinterIDByFBillNoAndMaterialId(sclkdFPo.getFBillNo(), fEntityS.get(i).getFItemID());
                LOGGER.info("materialRequisiteS:{}", materialRequisiteS);
                if(materialRequisiteS != null && !materialRequisiteS.getFInterID().isEmpty() && !materialRequisiteS.getFEntryID().isEmpty()){
                    fEntityS.get(i).setFInterID(materialRequisiteS.getFInterID());
                    fEntityS.get(i).setFEntryID(materialRequisiteS.getFEntryID());
                }else {
                    map.put("MSGCODE","1");
                    map.put("MSGNAME","error");
                    map.put("MSG",fEntityS.get(i).getMaterial_Name() + "请检查单据号、物料编码是否正确！");
                    return map;
                }

                if(fEntityS.get(i).getFInterID().isEmpty()  || fEntityS.get(i).getFEntryID().isEmpty()){
                    map.put("MSGCODE","1");
                    map.put("MSGNAME","error");
                    map.put("MSG","产品入库(红)反馈：表体明细ERP未获取到FinterID或FEntryID");
                    return map;
                }else{
                    kisMapper.updatesclkdS(fEntityS);
                }

            }
        }else {
            map.put("MSGCODE","1");
            map.put("MSGNAME","error");
            map.put("MSG","产品入库(红)反馈没表体");
            return map;
        }

        map.put("MSGCODE","0");
        map.put("MSGNAME","success");
        map.put("MSG","更新成功");
        return map;
    }

    @Override
    @Transactional
    public Map updateLldFeedBack(MaterialRequisiteF materialRequisiteF) {
        Map<String,Object> map = new HashMap<>();
        String FBillNo = materialRequisiteF.getFBillNo();

        //判断原单据是否已审核
        if(isIcstockBillCheck(FBillNo) == ConstantsDanju.DanjuStatus.CHECKED){
            map.put("MSGCODE","1");
            map.put("MSGNAME","error");
            map.put("MSG",FBillNo + "单据已审核，不允许修改！");
            return map;
        }
        //单据不存在
        if(isIcstockBillCheck(FBillNo) == ConstantsDanju.DanjuStatus.NODANJU){
            map.put("MSGCODE","1");
            map.put("MSGNAME","error");
            map.put("MSG",FBillNo + "单据不存在，请核实！");
            return map;
        }
        List<MaterialRequisiteS> fEntityS = materialRequisiteF.getFEntity();
        String frob = materialRequisiteF.getFROB();
        for (int i = 0; fEntityS != null && StringUtils.isNotEmpty(fEntityS) && i < fEntityS.size();i++){
            String s = kisMapper.queryItemIdByFNumber(fEntityS.get(i).getMaterial_Code());
            if(s == null || s.isEmpty()){
                map.put("MSGCODE","1");
                map.put("MSGNAME","error");
                map.put("MSG",fEntityS.get(i).getMaterial_Name() + "物料编码不存在");
                return map;
            }else{
                MaterialRequisiteS ma = kisMapper.queryFinterIDByFBillNoAndMaterialId(FBillNo,s);
                fEntityS.get(i).setFInterID(ma.getFInterID());
                fEntityS.get(i).setFEntryID(ma.getFEntryID());
            }
            if(frob.equals(ConstantsDanju.FROB.RED)){//判断领料单类型
                float v = Float.parseFloat(fEntityS.get(i).getFAuxQty());
                float v1 = Float.parseFloat(fEntityS.get(i).getFSecQty());
                if (v > 0 || v1 > 0){
                    map.put("MSGCODE","0");
                    map.put("MSGNAME","ERROR");
                    map.put("MSG","红色单据须负数入库");
                    return map;
                }
            }
        }

        int sCount = kisMapper.updateLldFQty(fEntityS);
        if(sCount > 0){
            map.put("MSGCODE","0");
            map.put("MSGNAME","SUCCESS");
            map.put("MSG","更新领料单{}条" + sCount);
            return map;
        }else {
            map.put("MSGCODE","1");
            map.put("MSGNAME","error");
            map.put("MSG","保存失败");
            return map;
        }

        /**


        //领料单获取最大FinterID
        String maxFinterID = getNewFinterID(Constants.TABLE_NAME.ICStockBill);
        materialRequisiteF.setFInterID(maxFinterID);
        //单据编号生成
        PoDanjuNumber poDanjuNumber = new PoDanjuNumber(ConstantsDanju.sclld.HEAD,ConstantsDanju.sclld.HEAD.length(),ConstantsDanju.sclld.FTRANTYPE);//加8：日期长度,+1从后面1位开始计算长度
        poDanjuNumber.setHeadyYyyyMMdd(poDanjuNumber.getHead().concat(poDanjuNumber.getYyyyMMdd()));//拼接出格式
        int sequence = kisMapper.queryOsInWareOrderFMaxID(poDanjuNumber);

        String lldNo = DanjuNumberUtil.getDanjuNumber(poDanjuNumber.getHead(),poDanjuNumber.getYyyyMMdd(),sequence);
        materialRequisiteF.setFBillNo(lldNo);
        //保存表头
        kisMapper.saveLldFeedBack(materialRequisiteF);
        //保存表体
        List<MaterialRequisiteS> fEntityS = materialRequisiteF.getFEntity();
        final int[] entryId = {1}; // 使用数组封装基本类型
        for (MaterialRequisiteS MaterialRequisiteS : fEntityS) {
//        fEntityS.forEach(MaterialRequisiteS -> {
            MaterialRequisiteS.setFInterID(materialRequisiteF.getFInterID());
            String FEntryID = kisMapper.getOutSourceEntrySMaxID(materialRequisiteF.getFInterID());
            LOGGER.info("领料单插入FEntryID:{}", FEntryID);
            if (FEntryID == null || FEntryID.equals("") || FEntryID.equals("0")){
                MaterialRequisiteS.setFEntryID(String.valueOf(entryId[0]));
                entryId[0]++;
            }
            String fItemId = kisMapper.queryItemIdByFNumber(MaterialRequisiteS.getMaterial_Code());
            if(fItemId == null || fItemId.isEmpty()){
                map.put("MSGCODE","1");
                map.put("MSG","物料编码不存在");
                return map;
            }
            MaterialRequisiteS.setFItemID(fItemId);//设置物料itemID
//            MaterialRequisiteS.setFEntryID(FEntryID == null ? "1" : FEntryID);
        };

        int sCount = kisMapper.saveLldFeedBackS(fEntityS);


        if(sCount > 0){
            map.put("MSGCODE","0");
            map.put("MSGNAME","SUCCESS");
            map.put("MSG","保存成功");
            return map;
        }else {
            map.put("MSGCODE","1");
            map.put("MSGNAME","error");
            map.put("MSG","保存失败");
            return map;
        }
        */

    }
    @Override
    @Transactional
    public Map updateLldReverseFeedBack(MaterialRequisiteF materialRequisiteF) {
        Map<String,Object> map = new HashMap<>();
        List<MaterialRequisiteS> fEntityS = materialRequisiteF.getFEntity();
        if (materialRequisiteF.getID().equals(ConstantsAccount.ZhiKu_1_FID)) {
            materialRequisiteF.setFBillerID(ConstantsAccount.ZhiKu_1_FBillerID);//制单人
            materialRequisiteF.setFSManagerID(ConstantsAccount.ZhiKu_1_FSManagerID);//保管人
            materialRequisiteF.setFCheckerID(ConstantsAccount.ZhiKu_1_FCheckerID);//审核人
            materialRequisiteF.setFFManagerID(ConstantsAccount.ZhiKu_1_FFManagerID);//验收人
        }
        for (int i = 0; fEntityS != null && StringUtils.isNotEmpty(fEntityS) && i < fEntityS.size();i++){
            String s = kisMapper.queryItemIdByFNumber(fEntityS.get(i).getMaterial_Code());
            if(s == null || s.isEmpty()){
                map.put("MSGCODE","1");
                map.put("MSGNAME","error");
                map.put("MSG",fEntityS.get(i).getMaterial_Name() + "物料编码不存在");
                return map;
            }else{
                MaterialRequisiteS ma = kisMapper.queryFinterIDByFBillNoAndMaterialId(materialRequisiteF.getFBillNo(),s);
                fEntityS.get(i).setFInterID(ma.getFInterID());
                fEntityS.get(i).setFEntryID(ma.getFEntryID());
            }

        }
        int sCount = kisMapper.updateLldFQtyReverseFeedBack(fEntityS);
        if(sCount > 0){
            map.put("MSGCODE","0");
            map.put("MSGNAME","SUCCESS");
            map.put("MSG","更新领料单{}条" + sCount);
            return map;
        }else {
            map.put("MSGCODE","1");
            map.put("MSGNAME","error");
            map.put("MSG","更新失败");
            return map;
        }



    }
    public Map saveLldFeedBackReverse(MaterialRequisiteF materialRequisiteF){
        Map<String,Object> map = new HashMap<>();

        //领料单获取最大FinterID
        String maxFinterID = getNewFinterID(Constants.TABLE_NAME.ICStockBill);
        materialRequisiteF.setFInterID(maxFinterID);
        //单据编号生成
        PoDanjuNumber poDanjuNumber = new PoDanjuNumber(ConstantsDanju.sclld.HEAD,ConstantsDanju.sclld.HEAD.length(),ConstantsDanju.sclld.FTRANTYPE);//加8：日期长度,+1从后面1位开始计算长度
        poDanjuNumber.setHeadyYyyyMMdd(poDanjuNumber.getHead().concat(poDanjuNumber.getYyyyMMdd()));//拼接出格式
        int sequence = kisMapper.queryOsInWareOrderFMaxID(poDanjuNumber);

        String lldNo = DanjuNumberUtil.getDanjuNumber(poDanjuNumber.getHead(),poDanjuNumber.getYyyyMMdd(),sequence);
        materialRequisiteF.setFBillNo(lldNo);
        //根据智库ID获取对应 人员
//        if (materialRequisiteF.getID().equals(Constants.ZHIKU.ZhiKu_1)){//智库1
//            materialRequisiteF.setFBillerID(Constants.ZHIKU.ZhiKu_1_FBillerID);//制单人
//            materialRequisiteF.setFSManagerID(Constants.ZHIKU.ZhiKu_1_FSManagerID);//保管人
//            materialRequisiteF.setFCheckerID(Constants.ZHIKU.ZhiKu_1_FCheckerID);//审核人
//            materialRequisiteF.setFFManagerID(Constants.ZHIKU.ZhiKu_1_FFManagerID);//验收人
////            zjdbdF.setFEmpID(Constants.ZHIKU.ZhiKu_1_FEmpID);业务人员
//        }else {
//            materialRequisiteF.setFBillerID(Constants.ZHIKU.ZhiKu_2_FBillerID);//制单人
//            materialRequisiteF.setFSManagerID(Constants.ZHIKU.ZhiKu_2_FSManagerID);//保管人
//            materialRequisiteF.setFCheckerID(Constants.ZHIKU.ZhiKu_2_FCheckerID);//审核人
//            materialRequisiteF.setFFManagerID(Constants.ZHIKU.ZhiKu_2_FFManagerID);//验收人
//        }
        if (materialRequisiteF.getID().equals(ConstantsAccount.ZhiKu_1_FID)) {
            materialRequisiteF.setFBillerID(ConstantsAccount.ZhiKu_1_FBillerID);//制单人
            materialRequisiteF.setFSManagerID(ConstantsAccount.ZhiKu_1_FSManagerID);//保管人
            materialRequisiteF.setFCheckerID(ConstantsAccount.ZhiKu_1_FCheckerID);//审核人
            materialRequisiteF.setFFManagerID(ConstantsAccount.ZhiKu_1_FFManagerID);//验收人
        }
        //保存表头
        kisMapper.saveLldFeedBackReverse(materialRequisiteF);
        //保存表体
        List<MaterialRequisiteS> fEntityS = materialRequisiteF.getFEntity();
        final int[] entryId = {1}; // 使用数组封装基本类型
        for (MaterialRequisiteS MaterialRequisiteS : fEntityS) {
//        fEntityS.forEach(MaterialRequisiteS -> {
            MaterialRequisiteS.setFInterID(materialRequisiteF.getFInterID());
            String FEntryID = kisMapper.getOutSourceEntrySMaxID(materialRequisiteF.getFInterID());
            LOGGER.info("领料单插入FEntryID:{}", FEntryID);
            if (FEntryID == null || FEntryID.equals("") || FEntryID.equals("0")){
                MaterialRequisiteS.setFEntryID(String.valueOf(entryId[0]));
                entryId[0]++;
            }
            String fItemId = kisMapper.queryItemIdByFNumber(MaterialRequisiteS.getMaterial_Code());
            if(fItemId == null || fItemId.isEmpty()){
                map.put("MSGCODE","1");
                map.put("MSG","物料编码不存在");
                return map;
            }
            MaterialRequisiteS.setFItemID(fItemId);//设置物料itemID
//            MaterialRequisiteS.setFEntryID(FEntryID == null ? "1" : FEntryID);
        };

        int sCount = kisMapper.saveLldFeedBackSReverse(fEntityS);


        if(sCount > 0){
            map.put("MSGCODE","0");
            map.put("MSGNAME","SUCCESS");
            map.put("MSG","保存成功");
            return map;
        }else {
            map.put("MSGCODE","1");
            map.put("MSGNAME","error");
            map.put("MSG","保存失败");
            return map;
        }
    }

    @Override
    @Transactional
    public Map<String, Object> insertXsckd(DispatchOrderF dispatchOrderF) {
        Map<String, Object> result = new HashMap<>();
        List<DispatchOrderS> detailList = dispatchOrderF.getFEntity();
        // 验证FROB FSelTranType是否对应
        boolean isValidType = (
                dispatchOrderF.getFROB().equals(ConstantsDanju.FROB.BLACK) && dispatchOrderF.getFSelTranType().equals(ConstantsDanju.FHTZD.FTRANTYPE + ""))
                ||
                (dispatchOrderF.getFROB().equals(ConstantsDanju.FROB.RED) && dispatchOrderF.getFSelTranType().equals(ConstantsDanju.THTZD.FTRANTYPE + ""));
        if (!isValidType) {
            return buildErrorResult(result, "单据类型FROB/FSelTranType不匹配，请核实后重新录入！");
        }
        // 检查上游单据
        for (DispatchOrderS detail : detailList) {
            String sourceBillNo = detail.getFSourceBillNo();
            if (sourceBillNo.contains(ConstantsDanju.THTZD.HEAD) || sourceBillNo.contains(ConstantsDanju.FHTZD.HEAD)) {
                int usedCount = kisMapper.ifTlOrSlHasBeenUsed(sourceBillNo);
                if (usedCount > 0) {
                    return buildErrorResult(result, "上游单据"+ sourceBillNo +"已被使用，请勿重复使用");
                }

                int existCount = kisMapper.ifFhOrThExists(sourceBillNo);
                if (existCount == 0) {
                    return buildErrorResult(result, "上游单据" + sourceBillNo + "不存在，请核实后重新录入！");
                }
            }
        }

        // 验证购货单位

        String customerID = VerifyBaseDataUtil.getCustomerID(dispatchOrderF.getFCustID(),
                dispatchOrderF.getSupplierCode(), kisMapper);
        if (StringUtils.isEmpty(customerID)) {
            return buildErrorResult(result, "购货单位不存在，请核实后重新录入！");
        }
        dispatchOrderF.setFCustID(customerID);
        LOGGER.info("supplierID:{}", dispatchOrderF.getFCustID());
        //如果FROB是-1去t_organization下找有无对应 供货单位 ，如果为1去t_supplier下找供货单位
//        if(dispatchOrderF.getFROB().equals(ConstantsDanju.FROB.RED)){
//            String customerID = VerifyBaseDataUtil.getCustomerID(dispatchOrderF.getFCustID(),
//                    dispatchOrderF.getSupplierCode(), kisMapper);
//            if (StringUtils.isEmpty(customerID)) {
//                return buildErrorResult(result, "购货单位不存在，请核实后重新录入！");
//            }
//            dispatchOrderF.setFCustID(customerID);
//            LOGGER.info("supplierID:{}", dispatchOrderF.getFCustID());
//        }else{
//            String customerID = VerifyBaseDataUtil.getSupplierID(dispatchOrderF.getFCustID(),
//                    dispatchOrderF.getSupplierCode(), kisMapper);
//            if (StringUtils.isEmpty(customerID)) {
//                return buildErrorResult(result, "购货单位不存在，请核实后重新录入！");
//            }
//            dispatchOrderF.setFCustID(customerID);
//            LOGGER.info("supplierID:{}", dispatchOrderF.getFCustID());
//        }


        // 验证部门
        String deptId = VerifyBaseDataUtil.getDeptID(dispatchOrderF.getFDeptID(),
                dispatchOrderF.getDepartmentCode(), kisMapper);
        if (StringUtils.isEmpty(deptId)) {
            return buildErrorResult(result, "部门不存在，请核实后重新录入！");
        }
        dispatchOrderF.setFDeptID(deptId);

        // 生成单据
        String maxFinterId = getNewFinterID(Constants.TABLE_NAME.ICStockBill);
        dispatchOrderF.setFInterID(maxFinterId);

        PoDanjuNumber poDanjuNumber = new PoDanjuNumber(
                ConstantsDanju.xsckd.HEAD,
                ConstantsDanju.xsckd.HEAD.length(),
                ConstantsDanju.xsckd.FTRANTYPE);
        poDanjuNumber.setHeadyYyyyMMdd(poDanjuNumber.getHead() + poDanjuNumber.getYyyyMMdd());
        int sequence = kisMapper.queryOsInWareOrderFMaxID(poDanjuNumber);

        String xsckdNo = DanjuNumberUtil.getDanjuNumber(
                poDanjuNumber.getHead(),
                poDanjuNumber.getYyyyMMdd(),
                sequence);
        dispatchOrderF.setFBillNo(xsckdNo);

        // 设置单据人员
//        if (Constants.ZHIKU.ZhiKu_1.equals(dispatchOrderF.getID())) {
//            dispatchOrderF.setFBillerID(Constants.ZHIKU.ZhiKu_1_FBillerID);
//            dispatchOrderF.setFSManagerID(Constants.ZHIKU.ZhiKu_1_FSManagerID);
//            dispatchOrderF.setFFManagerID(Constants.ZHIKU.ZhiKu_1_FFManagerID);
//        }
        if (dispatchOrderF.getID().equals(ConstantsAccount.ZhiKu_1_FID)) {
            dispatchOrderF.setFBillerID(ConstantsAccount.ZhiKu_1_FBillerID);//制单人
            dispatchOrderF.setFSManagerID(ConstantsAccount.ZhiKu_1_FSManagerID);//保管人
            dispatchOrderF.setFFManagerID(ConstantsAccount.ZhiKu_1_FFManagerID);//验收人
        }
        // 保存主表
        kisMapper.insertFhtzdFFeedBack(dispatchOrderF);

        // 处理明细
        detailList.sort(Comparator.comparingInt((DispatchOrderS s) -> Integer.parseInt(s.getFSourceEntryID())));//按原始单据EntryID排序
        int entryId = 1;
        for (DispatchOrderS detail : detailList) {
            detail.setFInterID(dispatchOrderF.getFInterID());
            String itemId = kisMapper.queryItemIdByFNumber(detail.getMaterial_Code());
            detail.setFItemID(itemId);

            String complexQty = detail.getFQty().substring(0, detail.getFQty().indexOf(".") + 1)
                    + detail.getCompany();
            detail.setFComplexQty(complexQty);

            detail.setFEntryID(String.valueOf(entryId++));

            // 仓库验证
            if (StringUtils.isEmpty(detail.getFDCStockID())) {
                if (StringUtils.isEmpty(detail.getFDCStockCode())) {
                    return buildErrorResult(result, "仓库编码不存在");
                }
                String stockId = kisMapper.queryWarehouseId(detail.getFDCStockCode());
                detail.setFDCStockID(stockId);
            }

            //获取源单据子表的FinterID、FEntryID赋值给外购入库单子表的FSourceInterID、FSourceEntryID
            DispatchOrderS dispatchOrderS = VerifyBaseDataUtil.getThShId(
                    detail.getFSourceBillNo(),
                    detail.getFItemID(),
                    kisMapper,
                    detail.getBatch_Number()
            );
            if (dispatchOrderS != null) {
                detail.setFSourceInterID(dispatchOrderS.getFSourceInterID());
                detail.setFSourceEntryID(dispatchOrderS.getFSourceEntryID());
                detail.setFEntryID(dispatchOrderS.getFSourceEntryID());
            }
            LOGGER.info("排序：{},entryID:{},sourceEntryID:{}",detail,entryId,detail.getFSourceEntryID());
        }

        // 保存明细
//        detailList.sort(Comparator.comparingInt((DispatchOrderS s) -> Integer.parseInt(s.getFSourceEntryID())));//按原始单据EntryID排序
        LOGGER.info("排序：{}",detailList);
        int sCount = kisMapper.insertFhtzdSFeedBack(detailList);
        if (sCount > 0) {
            return buildSuccessResult(result, "保存成功");
        }
        return buildErrorResult(result, "保存失败");
    }

    private Map<String, Object> buildErrorResult(Map<String, Object> map, String message) {
        map.put("MSGCODE", "1");
        map.put("MSGNAME", "ERROR");
        map.put("MSG", message);
        return map;
    }

    private Map<String, Object> buildSuccessResult(Map<String, Object> map, String message) {
        map.put("MSGCODE", "0");
        map.put("MSG", message);
        return map;
    }


    @Override
    public List<ZjdbdF> queryZjdbd() {
        final List<ZjdbdF> zjdbdF = kisMapper.queryZjdbdF();
        if (zjdbdF != null && zjdbdF.size() > 0){
            ListIterator<ZjdbdF> zjdbdFIterator = zjdbdF.listIterator();

            while (zjdbdFIterator.hasNext()){
                final ZjdbdF next = zjdbdFIterator.next();
                List<ZjdbdS> entityList = kisMapper.queryZjdbdS(next.getFInterID());
                next.setFEntity(entityList);
            }
//            kisMapper.updateKisICStockBillFlag(dispatchOrderF.get(0).getFInterID());
        }

        return zjdbdF;
//        return kisMapper.queryZjdbdF();
    }

    @Override
    public int insertZjdbdFeedBack(ZjdbdF zjdbdF) {
//        Map map =new HashMap<>();
//        map.put("TableName",Constants.ICStockBill);
        //kisMapper.getMaxFinterID(Constants.TABLE_NAME.ICStockBill)
        String maxFinterID = getNewFinterID(Constants.TABLE_NAME.ICStockBill);
        zjdbdF.setFInterID(maxFinterID);
//        if (zjdbdF.getID().equals(Constants.ZHIKU.ZhiKu_1)){//智库1
//            zjdbdF.setFBillerID(Constants.ZHIKU.ZhiKu_1_FBillerID);//制单人
//            zjdbdF.setFSManagerID(Constants.ZHIKU.ZhiKu_1_FSManagerID);//保管人
//            zjdbdF.setFCheckerID(Constants.ZHIKU.ZhiKu_1_FCheckerID);//审核人
//            zjdbdF.setFFManagerID(Constants.ZHIKU.ZhiKu_1_FFManagerID);//验收人
//        }
        if (zjdbdF.getID().equals(ConstantsAccount.ZhiKu_1_FID)){//智库1
            zjdbdF.setFBillerID(ConstantsAccount.ZhiKu_1_FBillerID);//制单人
            zjdbdF.setFSManagerID(ConstantsAccount.ZhiKu_1_FSManagerID);//保管人
            zjdbdF.setFCheckerID(ConstantsAccount.ZhiKu_1_FCheckerID);//审核人
            zjdbdF.setFFManagerID(ConstantsAccount.ZhiKu_1_FFManagerID);//验收人
//            zjdbdF.setFEmpID(ConstantsAccount.ZhiKu_1_FEmpID);业务人员
        }
        //单据编号生成
        PoDanjuNumber poDanjuNumber = new PoDanjuNumber(ConstantsDanju.DBD.HEAD, ConstantsDanju.DBD.HEAD.length(), ConstantsDanju.DBD.FTRANTYPE);//加8：日期长度,+1从后面1位开始计算长度
        poDanjuNumber.setHeadyYyyyMMdd(poDanjuNumber.getHead().concat(poDanjuNumber.getYyyyMMdd()));//拼接出格式
        int sequence = kisMapper.queryOsInWareOrderFMaxID(poDanjuNumber);
        String dbdFbillNo = DanjuNumberUtil.getDanjuNumber(poDanjuNumber.getHead(),poDanjuNumber.getYyyyMMdd(),sequence);
        zjdbdF.setFBillNo(dbdFbillNo);
        LOGGER.info("单据编号：{}",dbdFbillNo);
        int countFB = kisMapper.insertZjdbdFeedBack(zjdbdF);
        List<ZjdbdS> zjbdS = zjdbdF.getFEntity();

        final int[] entryId = {1}; // 使用数组封装基本类型
        zjbdS.forEach(temp -> {
            temp.setFInterID(zjdbdF.getFInterID());
            String FEntryID = kisMapper.getOutSourceEntrySMaxID(zjdbdF.getFInterID());
            System.out.println(FEntryID + ">>>>>>>>>");
            if (FEntryID == null || FEntryID.equals("")|| FEntryID.equals("0")){
                temp.setFEntryID(String.valueOf(entryId[0]));
                entryId[0]++;
            }else {
                temp.setFEntryID(FEntryID);
            }
        });
        kisMapper.insertZjdbdFeedBackS(zjbdS);
        return countFB;
    }

    @Override
    public List<PdResultF> queryPd() {
        final List<PdResultF> pdF = kisMapper.queryPdF();
        if (pdF != null && pdF.size() > 0){
            ListIterator<PdResultF> pdFIterator = pdF.listIterator();

            while (pdFIterator.hasNext()){
                final PdResultF next = pdFIterator.next();
                List<PdResultS> entityList = kisMapper.queryPdS(next.getFInterID());
                next.setFEntity(entityList);
            }
//            kisMapper.updateKisICStockBillFlag(dispatchOrderF.get(0).getFInterID());
        }
        return pdF;
    }

    @Override
    @Transactional
    public Map<String, Object> savePdStore(PdResultF pdResultF) {
        Map<String, Object> map = new HashMap<>();
        String maxFinterID = getNewFinterID(Constants.TABLE_NAME.ICStockBill);
        pdResultF.setFInterID(maxFinterID);
        if (pdResultF.getFTranType() !=null && StringUtils.isNotEmpty(pdResultF.getFTranType())){
            PoDanjuNumber poDanjuNumber;
            if(pdResultF.getFTranType().equals(ConstantsDanju.pdd.FTRANTYPE_PY + "")){//盘盈
                poDanjuNumber = new PoDanjuNumber(ConstantsDanju.pdd.HEAD_PY,ConstantsDanju.pdd.HEAD_PY.length(),ConstantsDanju.pdd.FTRANTYPE_PY);//加8：日期长度,+1从后面1位开始计算长度
                poDanjuNumber.setHeadyYyyyMMdd(poDanjuNumber.getHead().concat(poDanjuNumber.getYyyyMMdd()));//拼接出格式
                int sequence = kisMapper.queryOsInWareOrderFMaxID(poDanjuNumber);
                String pddPY = DanjuNumberUtil.getDanjuNumber(poDanjuNumber.getHead(),poDanjuNumber.getYyyyMMdd(),sequence);
                pdResultF.setFBillNo(pddPY);

            }else {//盘亏
                poDanjuNumber = new PoDanjuNumber(ConstantsDanju.pdd.HEAD_PK,ConstantsDanju.pdd.HEAD_PK.length(),ConstantsDanju.pdd.FTRANTYPE_PK);//加8：日期长度,+1从后面1位开始计算长度
                poDanjuNumber.setHeadyYyyyMMdd(poDanjuNumber.getHead().concat(poDanjuNumber.getYyyyMMdd()));//拼接出格式
                int sequence = kisMapper.queryOsInWareOrderFMaxID(poDanjuNumber);
                String pddPY = DanjuNumberUtil.getDanjuNumber(poDanjuNumber.getHead(),poDanjuNumber.getYyyyMMdd(),sequence);
                pdResultF.setFBillNo(pddPY);
            }
        }
        //根据智库ID设置单据头信息
        if (pdResultF.getID() != null && (pdResultF.getID().equals(ConstantsAccount.ZhiKu_1_FID) )){
//            pdResultF = (PdResultF) setDanjuPerson(pdResultF);
            if (pdResultF.getID() != null && pdResultF.getID().equals(ConstantsAccount.ZhiKu_1_FID)){
                pdResultF.setFBillerID(ConstantsAccount.ZhiKu_1_FBillerID);
                pdResultF.setFEmpID(ConstantsAccount.ZhiKu_1_FEmpID);
//                pdResultF.setFSManagerID(ConstantsAccount.ZhiKu_1_FSManagerID);
                pdResultF.setFFManagerID(ConstantsAccount.ZhiKu_1_FSManagerID);
            }
//            else if (pdResultF.getID() != null && pdResultF.getID().equals(ConstantsAccount.ZhiKu_2)) {
//                pdResultF.setFBillerID(ConstantsAccount.ZhiKu_2_FBillerID);
//                pdResultF.setFEmpID(ConstantsAccount.ZhiKu_2_FEmpID);
//                pdResultF.setFFManagerID(ConstantsAccount.ZhiKu_2_FSManagerID);
//            }
        }else {
            map.put("MSGCODE","1");
            map.put("MSGNAME","error");
            map.put("MSG","智库ID不存在");
            return map;
        }

        int countFB = kisMapper.insertPdFeedBack(pdResultF);//保存单据头

        List<PdResultS> zjbdS = pdResultF.getFEntity();
        final int[] entryId = {1}; // 使用数组封装基本类型
        for (PdResultS temp : zjbdS) {
            temp.setFInterID(maxFinterID);
            temp.setFEntryID(String.valueOf(entryId[0]));
            entryId[0]++;
            String s = kisMapper.queryItemIdByFNumber(temp.getMaterial_Code());

            if(s == null || s.isEmpty()){
                map.put("MSGCODE","1");
                map.put("MSGNAME","error");
                map.put("MSG",temp.getMaterial_Name() + "物料编码不存在");
                return map;
            }
            temp.setFItemID(s);
        }

        int i = kisMapper.insertPdFeedBackS(zjbdS);
        if(i > 0){
            map.put("MSGCODE","0");
            map.put("MSGNAME","SUCCESS");
            map.put("MSG","保存盘点单明细数据{}条" + countFB);
            return map;
        }else {
            map.put("MSGCODE","1");
            map.put("MSGNAME","error");
            map.put("MSG","保存失败");
            return map;
        }
    }

    @Override
    @Transactional
    public int saveZxckFeedBack(ZxckF zxckF) {
//        Map map =new HashMap<>();
//        map.put("TableName",Constants.TABLE_NAME.ICStockBill);
        String maxFinterID = getNewFinterID(Constants.TABLE_NAME.ICStockBill);
//        String maxFInterID = kisMapper.getMaxFinterID(Constants.TABLE_NAME.ICStockBill);
        List<ZxckS> fEntity = zxckF.getFEntity();
        zxckF.setFInterID(maxFinterID);
        if(StringUtils.isNotEmpty(zxckF.getDepartment()) && zxckF.getDepartment() != null){
            String deptID = kisMapper.queryDepartmentID(zxckF.getDepartment());
            zxckF.setDepartmentID(deptID);
        }
        final int[] entryId = {1}; // 使用数组封装基本类型
        fEntity.forEach(temp -> {
            temp.setFInterID(maxFinterID);//设置单据ID
            //TODO 根据名称查ID，有问题，是否会出现同步查询出多个的问题
            String unitID = kisMapper.queryUnitIdByFName(temp.getCompany());//根据单位名称获取单位ID
            temp.setFUnitID(unitID);
            String itemID = kisMapper.queryItemIdByFNumber(temp.getMaterial_Code());//根据物料编码获取ID
            temp.setFItemID(itemID);
            temp.setFEntryID(String.valueOf(entryId[0]));
            entryId[0]++;
//            String FEntryID = kisMapper.getOutSourceEntrySMaxID(zxckF.getFInterID());
//            if (FEntryID == null || FEntryID.equals("")){
//                temp.setFEntryID(String.valueOf(entryId[0]));
//                String itemId = kisMapper.queryItemIdByFNumber(temp.getMaterial_Code());//根据物料编码获取ID
//               temp.setFItemID(itemId);
//               String unitID = kisMapper.queryUnitIdByFName(temp.getCompany());//根据单位名称获取ID
//                temp.setFUnitID(unitID);
//                entryId[0]++;
//            }else {
//                temp.setFEntryID(FEntryID);
//            }
        });
        int countM = kisMapper.saveZxckFeedBack(zxckF);
        int countS = kisMapper.saveZxckSFeedBack(fEntity);
        return countM;
    }

    @Override
    @Transactional
    public int saveZxrkFeedBack(ZxrkF zxrkF) {
        String maxFInterID = getNewFinterID(Constants.TABLE_NAME.ICStockBill);
//        String maxFInterID = kisMapper.getMaxFinterID(Constants.TABLE_NAME.ICStockBill);
        List<ZxrkS> fEntity = zxrkF.getFEntity();
        zxrkF.setFInterID(maxFInterID);
        final int[] entryId = {1}; // 使用数组封装基本类型
        fEntity.forEach(temp -> {
            temp.setFInterID(maxFInterID);
            temp.setFEntryID(String.valueOf(entryId[0]));
            entryId[0]++;
            String itemId = kisMapper.queryItemIdByFNumber(temp.getMaterial_Code());//根据物料编码获取物料ID
            temp.setFItemID(itemId);
            String unitID = kisMapper.queryUnitIdByFName(temp.getCompany());//根据单位名称获取ID
            temp.setFUnitID(unitID);
//            String FEntryID = kisMapper.getOutSourceEntrySMaxID(zxrkF.getFInterID());
//            if (FEntryID == null || FEntryID.equals("")){
//                temp.setFEntryID(String.valueOf(entryId[0]));
//                String itemId = kisMapper.queryItemIdByFNumber(temp.getMaterial_Code());//根据物料编码获取ID
//                temp.setFItemID(itemId);
//                String unitID = kisMapper.queryUnitIdByFName(temp.getCompany());//根据单位名称获取ID
//                temp.setFUnitID(unitID);
//                entryId[0]++;
//            }else {
//                temp.setFEntryID(FEntryID);
//            }
        });
        int countM = kisMapper.saveZxrkFeedBack(zxrkF);
        int countS = kisMapper.saveZxrkSFeedBack(fEntity);
        return countM;
    }

    /**
     * 退料通知单
     * @return
     */
    @Override
    public List<TltzdF> querytltzdF() {
        final List<TltzdF> tltzdF = kisMapper.queryTltzdF();
        if (tltzdF != null && tltzdF.size() > 0){
            ListIterator<TltzdF> tltzdFIterator = tltzdF.listIterator();

            while (tltzdFIterator.hasNext()){
                final TltzdF next = tltzdFIterator.next();
                List<TltzdS> entityList = kisMapper.queryTltzdS(next.getFInterID());
                next.setFEntity(entityList);
            }
//            kisMapper.updateKisICStockBillFlag(dispatchOrderF.get(0).getFInterID());
        }
        return tltzdF;
    }

    @Override
    public List<ThtzdF> querythtzdF() {
        final List<ThtzdF> thtzdF = kisMapper.queryThtzdF();
        if (thtzdF != null && thtzdF.size() > 0){
            ListIterator<ThtzdF> thtzdFIterator = thtzdF.listIterator();

            while (thtzdFIterator.hasNext()){
                final ThtzdF next = thtzdFIterator.next();
                List<ThtzdS> entityList = kisMapper.queryThtzdS(next.getFInterID());
                next.setFEntity(entityList);
            }
        }
        return thtzdF;
    }

    @Override
    public int updateKisSEOutStockFlag(String fInterID,String kisFlag) {
        return kisMapper.updateKisSEOutStockFlag(fInterID, kisFlag);
    }


    @Override
    public MaterialRequisiteF querySctldF() {
        MaterialRequisiteF sctldF = kisMapper.querySctldF();
        if(sctldF != null ){
            String fInterID = sctldF.getFInterID();
            List<MaterialRequisiteS> sEntity = kisMapper.querySctldS(fInterID);
            sctldF.setFEntity(sEntity);
        }

        return sctldF;
    }

    @Override
    public Map updateZjdbd(ZjdbdF zjdbdF) {


        Map<String,Object> map = new HashMap<>();
        //判断原单据是否已审核
        if(isIcstockBillCheck(zjdbdF.getFBillNo()) == 1){
            map.put("MSGCODE","1");
            map.put("MSGNAME","error");
            map.put("MSG",zjdbdF.getFBillNo() + "单据已审核，不允许修改！");
            return map;
        }
        int count = kisMapper.queryCountICStockBillByFBillNo(zjdbdF);
        if(count != 1 ){
            map.put("MSGCODE","1");
            map.put("MSGNAME","error");
            map.put("MSG", "单据编码重复或不存在");
            return map;
        }
//        if (zjdbdF.getID().equals(Constants.ZHIKU.ZhiKu_1)){//智库1
//            zjdbdF.setFCheckerID(Constants.ZHIKU.ZhiKu_1_FCheckerID);//审核人
//        }else {
//            zjdbdF.setFCheckerID(Constants.ZHIKU.ZhiKu_2_FCheckerID);//审核人
//        }
        int i1 = kisMapper.updateZjdbd(zjdbdF);
        if(i1 == 1){
            map.put("MSGCODE","0");
            map.put("MSGNAME","SUCCESS");
            map.put("MSG","更新领料单{}条" + i1);
            return map;
        }else {
            map.put("MSGCODE","1");
            map.put("MSGNAME","error");
            map.put("MSG","更新失败");
            return map;
        }


/**
 *只更新审核人/审核时间,所以子表无需验证（谢主任要求不审核，只改数据日期：20250621）
 * 怕后期 会改回来，所以临时注释20250710
 */
        /*List<ZjdbdS> fEntityS = zjdbdF.getFEntity();
        for (int i = 0; fEntityS != null && StringUtils.isNotEmpty(fEntityS) && i < fEntityS.size();i++){
            String s = kisMapper.queryItemIdByFNumber(fEntityS.get(i).getFMaterialCode());
            if(s == null || s.isEmpty()){
                map.put("MSGCODE","1");
                map.put("MSGNAME","error");
                map.put("MSG",fEntityS.get(i).getFMaterialName() + "物料编码不存在");
                return map;
            }else{
                MaterialRequisiteS ma = kisMapper.queryFinterIDByFBillNoAndMaterialId(zjdbdF.getFBillNo(),s);
                fEntityS.get(i).setFInterID(ma.getFInterID());
                fEntityS.get(i).setFEntryID(ma.getFEntryID());
            }

        }*/


        /*int sCount = kisMapper.updateZjdbdS(fEntityS);//用于更新单据明细，目前只用wms确认即可，不需要更新数据
//        int sCount = kisMapper.updateZjdbd(zjdbdF);
        if(sCount > 0){
            map.put("MSGCODE","0");
            map.put("MSGNAME","SUCCESS");
            map.put("MSG","更新领料单{}条" + sCount);
            return map;
        }else {
            map.put("MSGCODE","1");
            map.put("MSGNAME","error");
            map.put("MSG","更新失败");
            return map;
        }*/

    }

    /**
     * 获取单据ID
     * @param tableName
     * @return
     */
    protected String getNewFinterID(String tableName){
//        select FMaxNum  from ICMaxNum where FTableName= 'ICStockBill' --1821
//        select * from IC_MaxNum where FTableName='ICStockBill'

        /*
        String FInterID = kisMapper.getMaxFinterID(tableName);//获取ICMaxNum中FMaxNum + 1;
        while (FInterID == null || FInterID.equals("")){//用while循环，在取得值后会出现已使用的问题，直到获取到不重复的主键ID
            FInterID = kisMapper.getICMaxNum(tableName);
            LOGGER.info("ICMaxNum表中最大可用FInterID:{}",FInterID);//
            String maxTableFinterID = kisMapper.getMaxTableFinterID(tableName);
            LOGGER.info("Table-max-FinterID:{}",maxTableFinterID);//

            if (FInterID != null && FInterID.length() > 0){
                kisMapper.updateIC_MaxNum(tableName,FInterID);
                LOGGER.info("update IC_MaxNum:{}",FInterID);//
                //判断表中是否已经使用了该主键
                int count = kisMapper.ifExistFinterID(tableName,FInterID);
                if(count > 0){
                    FInterID = null;
                    continue;
                }
            }else {
                FInterID = kisMapper.getMaxFinterID(tableName);//获取ICMaxNum中FMaxNum + 1
                LOGGER.info("getMaxFinterID:{}",FInterID);//10672
                if((Long.parseLong(maxTableFinterID) >= Long.parseLong(FInterID))){//判断表中主键与存储最大主键表中值比较
                    FInterID = String.valueOf(Long.parseLong(maxTableFinterID)+1);//使用表中最大主键+1
                    LOGGER.info("updateMaxTableFinterID+1后:{}",FInterID);//10673
                    kisMapper.updateIC_MaxNum(tableName,FInterID);//更新存储最大主键表中值
                    LOGGER.info("updateMaxTableFinterID:{}",FInterID);//10673
                }
//            FInterID = kisMapper.getMaxFinterID(tableName);
            }

        }*/
        String FInterID = null;
        while (FInterID == null){
            FInterID = kisMapper.getMaxFinterID(tableName);//获取ICMaxNum中对应表的FMaxNum
            LOGGER.info("getMaxFinterID(tableName):{}",FInterID);
            int updateIC_MaxNum = kisMapper.updateIC_MaxNum(tableName,FInterID);
            LOGGER.info("updateIC_MaxNum:{}",updateIC_MaxNum);
            kisMapper.updateICMaxNumFinterID(tableName, tableName);//更新最大码+1
//            kisMapper.updateICMaxNumPlusOne(FInterID);
            int count = kisMapper.ifExistFinterID(tableName,FInterID);
            if(count > 0){
                FInterID = null;
            }
        }
//        kisMapper.updateICMaxNumFinterID(tableName, tableName);//更新最大码
//        kisMapper.deleteIC_MaxNum(tableName);//删除IC_MaxNum表中关于【tableName】的有关选项
        return FInterID;
    }
    /**
     * 判断单据是否审核 0 未审核 1 已审核 101 无单据
     */
    protected int isIcstockBillCheck(String FBillNo){
        return kisMapper.isIcstockBillCheck(FBillNo);
    }
    /**
     * 单据人员设置
     * @param baseKisEntity
     * @return BaseKisEntity
     */
    protected BaseKisEntity setDanjuPerson(BaseKisEntity baseKisEntity){
        if (baseKisEntity.getID() != null && !baseKisEntity.getID().equals(ConstantsAccount.ZhiKu_1_FID)){
            baseKisEntity.setFBillerID(ConstantsAccount.ZhiKu_1_FBillerID);
            baseKisEntity.setFEmpID(ConstantsAccount.ZhiKu_1_FEmpID);
            baseKisEntity.setFSManagerID(ConstantsAccount.ZhiKu_1_FSManagerID);
        }
        return baseKisEntity;
    }


}
